# -*- coding: utf-8 -*-

class WarehouseController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:warehouseLock]

  #仓库设置页面。
  def warehouseList
    
  end

  #显示添加仓库页面
  def newWarehouse

  end

  #显示编辑仓库页面
  def editWarehouse
    
  end

  def getAllWarehouse
    forCBB = params[:for_cbb]
    if forCBB == 'true'
      warehouses = Warehouse.find(:all,:select=>'id,name',:conditions=>["is_locked = ?",0],:include=>[:warehouse_type])
    else
      warehouses = Warehouse.find(:all)
      #warehouses = Warehouse.findByName params[:query].to_s
    end

    if forCBB == 'true'
      jsonStr="{totalProperty:"+warehouses.length.to_s+",root:"+warehouses.to_json()+"}"
    else
      jsonStr="{totalProperty:"+warehouses.length.to_s+",root:"+warehouses.to_json(:include=>[:warehouse_type])+"}"
    end    
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
  def create
    begin
      warehouse = Warehouse.new()
      warehouse.company_id = session[:company_id]
      warehouse.number = params[:number]
      warehouse.name = params[:name]
      warehouse.warehouse_type_id = params[:warehouse_type_id]
      warehouse.description = params[:description]
      warehouse.save!
      info = "成功"
    rescue Exception => e
      info = e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #编辑前的数据准备
  def edit
    warehouse = Warehouse.find(params[:id],:include=>[:warehouse_type])
    rootStr = warehouse.to_json(:include=>{:warehouse_type=>{:only=>[:id,:name]}})
    jsonStr = "{root:["+rootStr+"]}"
    render :text=>jsonStr, :layout=>false
  end

  #把编辑后的数据，更新到数据库中
  def update
    begin
      warehouse = Warehouse.find(params[:id])
      warehouse.number = params[:number]
      warehouse.name = params[:name]
      warehouse.warehouse_type_id = params[:warehouse_type_id]
      warehouse.description = params[:description]
      warehouse.save!
      info = "成功"
    rescue Exception => e
      info = e.to_s
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #锁定或解锁仓库
  def warehouseLock
    warehouse = Warehouse.find(params[:id])
    if warehouse.is_locked == 1
      warehouse.is_locked = 0
    else
      warehouse.is_locked = 1
    end
    warehouse.save!
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
end
